package servlet.login;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import beans.Customer;
import service.CustomerService;

@WebServlet("/WechatLoginServlet")
public class WechatLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public WechatLoginServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		CustomerService service = new CustomerService();
		String code = request.getParameter("code");
		
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx759e6da18b169ee9&secret=9d022188d60983d15645c1b89d1b2f7e&code="
				+ code + "&grant_type=authorization_code";
		String json = sendGet(url);
		JsonObject returnData = new JsonParser().parse(json).getAsJsonObject();
		String openid = returnData.get("openid").getAsString();
		Customer customer = service.getCustomerByWechat(openid);
		if (customer == null || customer.getUsername() == null || customer.getUsername().equals("")) {
			response.sendRedirect(request.getContextPath() + "/login.html?wechat=" + openid);
		}else {
			request.getSession().setAttribute("customer", customer);
			response.sendRedirect(request.getContextPath() + "/index.html");
		}
	}

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url) {
		StringBuilder result = new StringBuilder();
		BufferedReader in = null;
		try {
			String urlNameString = url;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 建立实际的连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			System.err.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result.toString();
	}
}
